package com.aranandroid.customview.squareview

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.annotation.Nullable
import androidx.core.view.children
import com.aranandroid.customview.R
import com.aranandroid.customview.squareview.base.SquareView

class SquareRadioGroup(
    @Nullable context: Context?,
    @Nullable attrs: AttributeSet?
) : RadioGroup(context!!, attrs) {
    var squareView: SquareView
    // 选中的值
    var radioCheckValue: String? = null
        get() {
            return field
        }
        set(value) {
            field = value
            // 根据选中的值设置 选中数据
            if (childCount > 0) {
                for (child in children) {
                    if (child is SquareRadioButton) {
                        if (child.radioValue?.equals(radioCheckValue) == true) {
                            check(child.id)
                        }
                    }
                }
            }
        }

    // 选中的值改变回调（用于扩展属性BindingAdapters、请自己实现）
    var changeRadioCheckValue: (String?)->Unit = {}

    init {
        squareView = SquareView(context, attrs, 0, this)
        val obtainStyledAttributes =
            context!!.obtainStyledAttributes(attrs, R.styleable.SquareRadioGroup)
        // 选中的值
        radioCheckValue =
            obtainStyledAttributes.getString(R.styleable.SquareRadioGroup_radio_check_value)
        setOnCheckedChangeListener(null)
    }

    constructor(context: Context?) : this(context, null)

    override fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
        super.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
                // 监听一下 选中时候改变radioCheckValue的值
                val button = group?.findViewById<RadioButton>(checkedId)
                if (button is SquareRadioButton) {
                    radioCheckValue = button.radioValue
                    // 选中的值改变回调
                    changeRadioCheckValue(radioCheckValue)
                }
                listener?.onCheckedChanged(group, checkedId)
            }

        })
    }

    override fun dispatchDraw(canvas: Canvas?) {
        super.dispatchDraw(canvas)
        // 初始化的时候 根据选中的值设置 选中数据
        radioCheckValue = radioCheckValue
    }

}